# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import http, tools, _
from odoo.http import request, content_disposition, Response
from wechatpy.utils import check_signature
from wechatpy.exceptions import InvalidSignatureException, InvalidAppIdException
from wechatpy.oauth import WeChatOAuth


class WechatCallBack(http.Controller):
    @http.route('/wechat/callback', type='http', auth='none', methods=['GET', 'POST'])
    def wechat_callback(self, **args):
        """

        :param args: {'signature': '48dbc27e9958989113bc9a78d436941d24862578', 'echostr': '4809183747737386431', 'timestamp': '1734770062', 'nonce': '831734485'}
        :return:
        """
        if request.httprequest.method == 'GET':
            try:
                check_signature(tools.config['wechat_token'], args.get('signature'), args.get('timestamp'),
                                args.get('nonce'))
                return request.make_response(args.get('echostr'))
            except (InvalidAppIdException, InvalidSignatureException):
                # 验证失败
                return request.make_response("Invalid signature", status=403)
        if request.httprequest.method == 'POST':
            # TODO
            return request.make_response('ok')

    @http.route('/wechat/auth', type='http', auth='none', methods=['GET'])
    def wechat_auth(self, **args):
        oauth = WeChatOAuth(tools.config['wechat_appid'], tools.config['wechat_secret'],
                            'https://www.cdryxjs.com/wechat/login', 'snsapi_userinfo',
                            state=args.get('state', 'default'))
        print(oauth.authorize_url)
        return Response("""<html><head><script>
                window.location = "%s";
            </script></head><body></body></html>""" % oauth.authorize_url)

    @http.route('/wechat/login', type='http', auth='none', methods=['GET'])
    def wechat_login(self, **args):
        try:
            # print(args)
            # {'code': '071fX8ml28KmIe4G6dnl2AENMf2fX8mu', 'state': '12233xxx'}
            oauth = WeChatOAuth(tools.config['wechat_appid'], tools.config['wechat_secret'], '/wechat/login')
            oauth.fetch_access_token(args.get('code'))
            user_info = oauth.get_user_info()
            # print(oauth.get_user_info())
            # user_info = {'openid': 'ogyrm67Iq7AXm1x4CUjEwz1uVif8', 'nickname': 'wayen', 'sex': 0, 'language': '',
            #              'city': '',
            #              'province': '', 'country': '',
            #              'headimgurl': 'https://thirdwx.qlogo.cn/mmopen/vi_32/T9TkC61W1gp3v00YUmtUrFI7M6QGeRsS7PFL3mbNMA0y1czJY6u21gsQy08LzO4BnugcFq5bnJ8SKNm6vr77oQ/132',
            #              'privilege': []}

            login = user_info['openid']
            user = request.env['res.users'].sudo().search([('email', '=', login)], limit=1)
            if not user:
                request.env['res.users'].sudo().with_context(mail_create_nolog=True).signup({
                    'login': login, 'name': user_info['nickname']
                }
                )
                user = request.env['res.users'].sudo().search([('email', '=', login)], limit=1)
            if user:
                request.from_wechat = True
                request.session.authenticate(request.db, login, 'password')
                return request.redirect(args.get('state', '/shop'))
            else:
                return request.redirect('/wechat/auth')
        except Exception as e:
            return request.redirect('/wechat/auth')
